package com.hmkj.core.service.user.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.utils.*;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.constant.Enum;
import com.hmkj.core.constant.SessionId;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.mapper.account.AccountLogMapper;
import com.hmkj.core.mapper.account.AccountMapper;
import com.hmkj.core.mapper.account.AccountSimulationMapper;
import com.hmkj.core.mapper.order.OrderMapper;
import com.hmkj.core.mapper.seller.SellerMapper;
import com.hmkj.core.mapper.simulation.SubscribeMapper;
import com.hmkj.core.mapper.system.AdminMapper;
import com.hmkj.core.mapper.user.UserMapper;
import com.hmkj.core.mapper.user.UserNoticeSetMapper;
import com.hmkj.core.mapper.userFreeze.UserFreezeMapper;
import com.hmkj.core.mapper.userIdentify.UserIdentifyMapper;
import com.hmkj.core.mapper.userInfo.UserInfoMapper;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.account.Account;
import com.hmkj.core.po.account.AccountLog;
import com.hmkj.core.po.account.AccountSimulation;
import com.hmkj.core.po.invest.Invest;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.seller.Seller;
import com.hmkj.core.po.simulation.Subscribe;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.user.UserNoticeSet;
import com.hmkj.core.po.userFreeze.UserFreeze;
import com.hmkj.core.po.userIdentify.UserIdentify;
import com.hmkj.core.po.userInfo.UserInfo;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.cache.SessionService;
import com.hmkj.core.service.invest.InvestService;
import com.hmkj.core.service.user.UserService;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户业务相关Service接口实现<br>
 *
 * @author donfy
 * @ClassName: UserServiceImpl
 * @date 2017-08-15 03:03:30
 */
@Slf4j
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AccountLogMapper accountLogMapper;
    @Resource
    private UserFreezeMapper userFreezeMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserIdentifyMapper userIdentifyMapper;
    @Resource
    private AccountSimulationMapper accountSimulationMapper;
    @Resource
    private SubscribeMapper subscribeMapper;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private SellerMapper sellerMapper;
    @Resource
    private UserNoticeSetMapper userNoticeSetMapper;
    @Resource
    private InvestService investService;
    @Resource
    private SessionService sessionService;
    @Resource
    private RedisService redisService;

    @Override
    public GenericMapper<User, Integer> _getMapper() {
        return userMapper;
    }

    @Override
    public void resetPwd(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new BussinessException("用户信息有误");
        }
        userMapper.updateByPrimaryKeySelective(new User(t -> {
            t.setId(id);
            t.setPassword(MD5Utils.getMd5("a123123"));
        }));
    }

    @Override
    public void doRegister(final UserModel userModel) {
        log.info("注册service");
        userModel.checkRegister();
        String mobilePhone = userModel.getMobilePhone();
        // 校验手机号是否被注册
        if (userMapper.selectCount(new User(u -> u.setMobilePhone(mobilePhone))) > 0) {
            throw new BussinessException("当前手机号已被注册");
        }
        User uSave = new User();
        uSave.setResource(userModel.getResource());
        uSave.setMobilePhone(userModel.getMobilePhone());
        // 初始化层级code
        if (userModel.getInviteId() == null) {
            Integer pc = userMapper.countTopByLevel();
            uSave.setCode((pc + 1) + "");
            uSave.setLevel(1);
        } else {// 有父级
            final User parent = userMapper.selectByPrimaryKey(userModel.getInviteId());
            Integer pc = countPartnerByLevel(parent.getCode(), 1);
            uSave.setCode(parent.getCode() + "." + (pc + 1));
            uSave.setLevel(parent.getLevel() == null ? 1 : parent.getLevel() + 1);
            uSave.setInviteId(parent.getId());
        }
        // 解密密码并md5加密保存
        uSave.setPassword(userModel.encodePwd(userModel.decryptPwd()));
        //生成idCode
        User checkUser = null;
        String generateCode = "";
        //邀请码最小长度
//        Integer codeFixed = 6;
//        Integer count = 1;
//        do {
//            if (count % 10 == 0) {
//                codeFixed++;
//            }
//            generateCode = RandomUtils.generateInveterCode(codeFixed);
//            checkUser = userMapper.selectByInviteCode(generateCode);
//            count++;
//        } while (null != checkUser);
        uSave.setInviteCode(mobilePhone);
        uSave.setUserName(StrUtil.sub(mobilePhone, 0, 2) + "****" + StrUtil.sub(mobilePhone, 9, mobilePhone.length()));
        uSave.setRegisterTime(DateUtils.getNow());
        userMapper.insert(uSave);
        final User user = userMapper.selectOne(new User(u -> u.setMobilePhone(userModel.getMobilePhone())));
        // 初始化 account 账户
        accountMapper.insert(new Account(t -> {
            t.setUserId(user.getId());
        }));
        //初始化用户冻结表
        userFreezeMapper.insert(new UserFreeze(t -> {
            t.setUserId(user.getId());
        }));
        //初始化用户信息
        userInfoMapper.insert(new UserInfo(t -> {
            t.setUserId(user.getId());
        }));
        //初始化用户认证
        userIdentifyMapper.insert(new UserIdentify(t -> {
            t.setUserId(user.getId());
        }));
        //初始化模拟账户
        accountSimulationMapper.insert(new AccountSimulation(t -> {
            t.setUserId(user.getId());
            t.setTotal(redisService.get(ConfigNID.SIMULATION_MONEY, BigDecimal.class));
            t.setAvailable(redisService.get(ConfigNID.SIMULATION_MONEY, BigDecimal.class));
        }));
        //初始化高手
        subscribeMapper.insert(new Subscribe(t -> {
            t.setUserId(user.getId());
        }));
        //初始化消息推送
        userNoticeSetMapper.insert(new UserNoticeSet(t->{
            t.setUserId(user.getId());
        }));
    }

    @Override
    public Integer countPartnerByLevel(String code, int level) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isBlank(code)) {
            params.put("level", 0);
            params.put("offset", 0);
            return userMapper.countPartnerByLevel(params);
        }

        params.put("code", code);
        if (level != 0) {
            // 计算偏移量（用户本身节点标识中的点的数量）
            int offset = code.length() - code.replace(".", "").length();
            params.put("level", level);
            params.put("offset", offset);
        }
        return userMapper.countPartnerByLevel(params);
    }

    @Override
    public List<User> listPartnerByLevel(String code, int level) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isBlank(code)) {
            params.put("level", 0);
            params.put("offset", 0);
            return userMapper.listPartnerByLevel(params);
        }

        params.put("code", code);
        if (level != 0) {
            // 计算偏移量（用户本身节点标识中的点的数量）
            int offset = code.length() - code.replace(".", "").length();
            params.put("level", level);
            params.put("offset", offset);
        }
        return userMapper.listPartnerByLevel(params);
    }

    @Override
    public void updateUserToBandingMailbox(User user, String email) {
        updateByPrimaryKeySelective(new User(u -> {
            u.setId(user.getId());
            u.setEmail(email);
        }));
    }

    @Override
    public User selectByInviteCode(String inviteCode) {
        return userMapper.selectByInviteCode(inviteCode);
    }

    @Override
    public User selectByMobile(String mobile) {
        return userMapper.selectByMobile(mobile);
    }

    @Override
    public void updateUserMobile(Integer userId, String newUserMobilePhone) {

    }

    @Override
    public User realName(final User user) {
        //校验身份证号码重复
        int m = userMapper.selectCount(new User(cpu -> {
            cpu.setIdCard(user.getIdCard());
            cpu.setDelFlag(UserModel.DELFLAG.NORMAL.code);
        }));
        if (m > 0) {
            throw new BussinessException("身份证号码已存在,请检查身份证号码是否正确");
        }
        int i = userMapper.updateByPrimaryKeySelective(new User(u -> {
            u.setRealName(user.getRealName());
            u.setIdCard(user.getIdCard());
            u.setId(user.getId());
        }));
        if (i != 1) throw new BussinessException("实名认证提交失败");
        return userMapper.selectOne(user);
    }

    @Override
    public User doLogin(final UserModel model, HttpServletRequest request) {
//        try {
//            PowerOption.powerAuth();
//        } catch (Exception e) {
//            throw new BussinessException("登录异常");
//        }
        final User user = userMapper.selectOne(new User(u -> u.setMobilePhone(model.getMobilePhone())));
//         保存登录ip 最后登录时间
        userMapper.updateByPrimaryKeySelective(new User(u -> {
            u.setId(user.getId());
            u.setLastLoginIp(model.getLastLoginIp());
        }));
        // 登录动作
        String sessionId = sessionService.setSession(SessionId.MEMBER_USER, user, request);
        userMapper.updateByPrimaryKeySelective(new User(u -> {
            u.setId(user.getId());
            u.setHid(sessionId);
        }));
        return null;
    }

    @Override
    public void editInvestor(Integer id, Integer inviteId) throws Exception {
    }

    @Override
    public void addAdminAgent(User user) throws Exception {
        //校验上级
        Integer level = user.getLevel();
        Integer parentId = user.getInviteId();
        Integer userType = user.getUserType();
        User parentUser = null;

        if (level > 1) {
            //检验上级
            for (int i = level - 1; i > 0; i--) {
                parentUser = userMapper.selectByPrimaryKey(parentId);
                Integer p = parentUser.getUserType();
                if (p == Enum.UserType.AGENTSELLER.getValue() || p == Enum.UserType.NEXTSELLER.getValue()) {
                    throw new BussinessException("添加的用户上级不能存在同级或低级代理商或者销售");
                }
                if (userType == Enum.UserType.ONELEVEL.getValue()) {
                    if (p == Enum.UserType.ONELEVEL.getValue() || p == Enum.UserType.TWOLEVEL.getValue() || p == Enum.UserType.THREELEVEL.getValue()) {
                        throw new BussinessException("添加的用户上级不能存在同级或低级代理商或者销售");
                    }
                }
                if (userType == Enum.UserType.TWOLEVEL.getValue()) {
                    if (p == Enum.UserType.TWOLEVEL.getValue() || p == Enum.UserType.THREELEVEL.getValue()) {
                        throw new BussinessException("添加的用户上级不能存在同级或低级代理商或者销售");
                    }
                }
                if (userType == Enum.UserType.THREELEVEL.getValue()) {
                    if (p == Enum.UserType.THREELEVEL.getValue()) {
                        throw new BussinessException("添加的用户上级不能存在同级或低级代理商或者销售");
                    }
                }
                parentId = parentUser.getInviteId();
                userType = parentUser.getUserType();
            }
        }

        //校验下级
        Map<String, Object> param = new HashMap<>();
        param.put("code", user.getCode());
        param.put("level", null);
        List<User> userList = userMapper.listPartnerByLevel(param);
        for (User n : userList) {
            Integer t = n.getUserType();
            if (t == Enum.UserType.AGENTSELLER.getValue() || t == Enum.UserType.NEXTSELLER.getValue() || t == Enum.UserType.ONELEVEL.getValue() || t == Enum.UserType.TWOLEVEL.getValue() || t == Enum.UserType.THREELEVEL.getValue()) {
                throw new BussinessException("添加的用户下级不能存在代理商或者销售");
            }
        }

        userMapper.updateByPrimaryKeySelective(user);
        //admin添加代理商
        Admin admin = new Admin();
        if (user.getUserType() == Enum.UserType.ONELEVEL.getValue()) {
            admin.setRoleId(Enum.ONE_ROLE_ID);
            admin.setRoleName(Enum.ONE_ROLE_NAME);
            admin.setType(Enum.ONE_TYPE);
        } else if (user.getUserType() == Enum.UserType.TWOLEVEL.getValue()) {
            admin.setRoleId(Enum.TWO_ROLE_ID);
            admin.setRoleName(Enum.TWO_ROLE_NAME);
            admin.setType(Enum.TWO_TYPE);
        } else {
            admin.setRoleId(Enum.THREE_ROLE_ID);
            admin.setRoleName(Enum.THREE_ROLE_NAME);
            admin.setType(Enum.THREE_TYPE);
        }
        admin.setPassword(user.getPassword());
        admin.setName(user.getMobilePhone());
        admin.setUserId(user.getId());
        admin.setStatus(Integer.valueOf(Enum.Status.ON.getValue()));
        adminMapper.insert(admin);
    }

    @Override
    public DtGrid getProfitReportl(DtGrid dtGrid, Admin admin) throws Exception {
        Map<String, Object> dtGridFastQueryParameters = dtGrid.getFastQueryParameters();
        //获取所有代理商及次级销售、代理商销售
        if (dtGridFastQueryParameters.get("ge_settleStartTime") != null && dtGridFastQueryParameters.get("le_settleEndTime") != null) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String settleStartTime = dtGridFastQueryParameters.get("ge_settleStartTime").toString();
            String settleEndTime = dtGridFastQueryParameters.get("le_settleEndTime").toString();
            Date startTime = simpleDateFormat.parse(settleStartTime);
            Date endTime = simpleDateFormat.parse(settleEndTime);
            //删除时间参数
            dtGridFastQueryParameters.remove("ge_settleStartTime");
            dtGridFastQueryParameters.remove("le_settleEndTime");

            if (admin.getRoleId() == Enum.ONE_ROLE_ID || admin.getRoleId() == Enum.TWO_ROLE_ID || admin.getRoleId() == Enum.THREE_ROLE_ID
                    || admin.getRoleId() == Enum.NEXT_SELLER_ROLE_ID || admin.getRoleId() == Enum.AGENT_SELLER_ROLE_ID) {
                User u = userMapper.selectByPrimaryKey(admin.getUserId());
                Map<String, Object> data = new HashMap<>();
                data.put("code", u.getCode());
                data.put("level", 0);
                String userIds = "0";
                List<User> userList = userMapper.listPartnerByLevel(data);
                if (CollectionUtils.isNotEmpty(userList)) {
                    userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
                }
                dtGridFastQueryParameters = dtGrid.getFastQueryParameters();
                dtGridFastQueryParameters.put("in_id", userIds);
                dtGrid.setFastQueryParameters(dtGridFastQueryParameters);
                dtGrid = getDtGridList(dtGrid, UserModel.class);
                if (dtGrid.getExhibitDatas() != null && dtGrid.getExhibitDatas().size() > 0) {
                    for (Object obj : dtGrid.getExhibitDatas()) {
                        LinkedHashMap map = (LinkedHashMap) obj;
                        UserModel user = (UserModel) userMapper.selectByPrimaryKey(map.get("userId"));
                        if (user.getUserType() == Enum.UserType.NEXTSELLER.getValue()) {
                            nextSeller(user, startTime, endTime);
                        } else if (user.getUserType() == Enum.UserType.THREELEVEL.getValue()) {
                            threeAgent(user, startTime, endTime);
                            findParent(user, Enum.UserType.TWOLEVEL.getValue());
                        } else if (user.getUserType() == Enum.UserType.TWOLEVEL.getValue()) {
                            twoAgent(user, startTime, endTime);
                            findParent(user, Enum.UserType.ONELEVEL.getValue());
                        } else if (user.getUserType() == Enum.UserType.ONELEVEL.getValue()) {
                            oneAgent(user, startTime, endTime);
                        } else if (user.getUserType() == Enum.UserType.AGENTSELLER.getValue()) {
                            agentSeller(user, startTime, endTime);
                            findParent(user, Enum.UserType.ONELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue(), Enum.UserType.THREELEVEL.getValue());
                        }
                    }
                }
            } else if (admin.getRoleId() == Enum.PLATFORM_ROLE_ID) {
                List<Object> list = new ArrayList<>();
                User user = userMapper.selectByPrimaryKey(1);
                UserModel platUser = new UserModel();
                BeanUtils.copyProperties(user,platUser);
                BigDecimal platFee = BigDecimal.ZERO;//手续费总利润
                BigDecimal platProfit = BigDecimal.ZERO;//盈利总利润
                BigDecimal platDefer = BigDecimal.ZERO;//递延费总利润
                Map<String, Object> param1 = new HashMap<>();
                param1.put("startTime", startTime);
                param1.put("endTime", endTime);
                param1.put("status", Order.STATUS.T7.code);
                List<Order> orderList = orderMapper.selectOrderAllWithTime(param1);
                //1.利润分成
                if (CollectionUtils.isNotEmpty(orderList)) {
                    for (Order order : orderList) {
                        List<User> userList = getParentUsers(order.getUserId(), Enum.UserType.NEXTSELLER.getValue(), Enum.UserType.ONELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.AGENTSELLER.getValue());
                        HashMap<Integer, Object> typeMap = new HashMap<>();
                        if (CollectionUtils.isNotEmpty(userList)) {
                            for (User u : userList) {
                                typeMap.put(u.getUserType(), u);
                            }
                            //订单的综合管理费
                            BigDecimal platformProfit = order.getPaidFee();
                            BigDecimal defer = order.getPaidDiyan();
                            //存在上级代理商或销售时处理
                            Map<Integer, BigDecimal> mapB = agent(typeMap, order, platformProfit, platFee, platProfit, defer, platDefer);
                            platProfit = mapB.get(1);
                        } else {
                            if (order.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                                BigDecimal proDivideScale = new BigDecimal(1).subtract(order.getDivideScale());
                                //可分佣盈利利润
                                BigDecimal proDivide = order.getProfitCount().multiply(proDivideScale);
                                platProfit = platProfit.add(proDivide);//盈利利润
                            }
                        }
                    }
                }
                //2.综合管理费
                Map<String, Object> param2 = new HashMap<>();
                param2.put("startTime", startTime);
                param2.put("endTime", endTime);
                List<Order> orderList2 = orderMapper.selectOrderAllWithTime(param2);
                if (CollectionUtils.isNotEmpty(orderList)) {
                    for (Order order : orderList2) {
                        List<User> userList = getParentUsers(order.getUserId(), Enum.UserType.NEXTSELLER.getValue(), Enum.UserType.ONELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.AGENTSELLER.getValue());
                        HashMap<Integer, Object> typeMap = new HashMap<>();
                        if (CollectionUtils.isNotEmpty(userList)) {
                            for (User u : userList) {
                                typeMap.put(u.getUserType(), u);
                            }
                            //订单的综合管理费
                            BigDecimal platformProfit = order.getPaidFee();
                            BigDecimal defer = order.getPaidDiyan();
                            //存在上级代理商或销售时处理
                            Map<Integer, BigDecimal> mapB = agent(typeMap, order, platformProfit, platFee, platProfit, defer, platDefer);
                            platFee = mapB.get(0);
                        } else {
                            platFee = platFee.add(order.getPaidFee());
                        }
                    }
                }
                //3.递延费分成
                Map<String, Object> param3 = new HashMap<>();
                param3.put("startTime", startTime);
                param3.put("endTime", endTime);
                param3.put("type", AccountLog.TYPE.T12.code);
                List<AccountLog> accountLogList = accountLogMapper.selectAccountLogAllWithTime(param3);
                if (CollectionUtils.isNotEmpty(accountLogList)) {
                    for (AccountLog accountLog : accountLogList) {
                        List<User> userList = getParentUsers(accountLog.getUserId(), Enum.UserType.NEXTSELLER.getValue(), Enum.UserType.ONELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.AGENTSELLER.getValue());
                        HashMap<Integer, Object> typeMap = new HashMap<>();
                        if (CollectionUtils.isNotEmpty(userList)) {
                            for (User u : userList) {
                                typeMap.put(u.getUserType(), u);
                            }
                            Map<Integer, BigDecimal> mapB = agent(typeMap, accountLog.getAmount(), platDefer);
                            platDefer = mapB.get(0);
                        }
                    }
                }
                platUser.setPoundageDivide(PriceHelper.format(platFee));
                platUser.setProfitDivide(PriceHelper.format(platProfit));
                platUser.setSellerDivide(BigDecimal.ZERO);
                platUser.setDeferDivide(platDefer);
                platUser.setTotalDivide(PriceHelper.format(platFee).add(PriceHelper.format(platProfit)).add(PriceHelper.format(platDefer)));
                list.add(platUser);
                dtGrid.setExhibitDatas(list);
                dtGrid.setRecordCount(dtGrid.getRecordCount() + 1);
            }
        } else {
            dtGrid.setExhibitDatas(new ArrayList<>());
        }
        return dtGrid;
    }

    /**
     * 次销售
     *
     * @param user
     * @param startTime
     * @param endTime
     * @throws Exception
     */
    private void nextSeller(UserModel user, Date startTime, Date endTime) throws Exception {
        //获取对应角色下用户所有订单
        List<Order> orderList = getRoleOrder1(user, startTime, endTime);
        BigDecimal sellerFee = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(orderList)) {
            for (Order o : orderList) {
                Seller seller = sellerMapper.selectOne(new Seller(t -> {
                    t.setUserId(o.getUserId());
                }));
                //次销售佣金
                BigDecimal sellerFee2 = PriceHelper.format(o.getTradeCredit().multiply(BigDecimal.valueOf(10000)).multiply(seller.getFeeScale()));
                sellerFee = sellerFee.add(sellerFee2);
            }
        }
        user.setSellerDivide(sellerFee);
        user.setPoundageDivide(BigDecimal.ZERO);
        user.setProfitDivide(BigDecimal.ZERO);
        user.setTotalDivide(sellerFee);
    }

    /**
     * 三级代理商获利计算
     */
    private void threeAgent(UserModel user, Date startTime, Date endTime) throws Exception {
        //1.盈利分成
        //获取对应角色下用户所有已结算订单
        List<Order> orderList1 = getRoleOrder1(user, startTime, endTime);
        BigDecimal agentFee = BigDecimal.ZERO;
        BigDecimal agentProfit = BigDecimal.ZERO;
        BigDecimal deferFee = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(orderList1)) {
            for (Order o : orderList1) {
                //当前订单的是否盈利
                BigDecimal agentProfit3 = BigDecimal.ZERO;
                if (o.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal proDivideScale = new BigDecimal(1).subtract(o.getDivideScale());
                    //可分佣盈利利润
                    BigDecimal proDivide = o.getProfitCount().multiply(proDivideScale);
                    //获取当前代理商的盈利分佣比例
                    BigDecimal agentProfitScale = user.getProfitScale();
                    //代理商从盈利中获得的佣金
                    agentProfit3 = agentProfitScale.multiply(proDivide).multiply(BigDecimal.valueOf(0.01));
                }
                //判当前订单的客户上级是否有代理商销售
                List<User> usersList = getParentUsers(o.getUserId(), Enum.UserType.AGENTSELLER.getValue());

                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Seller seller = sellerMapper.selectOne(new Seller(t -> {
                        t.setUserId(usersList.get(0).getId());
                    }));
                    if (agentProfit3.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal proSeller = agentProfit3.multiply(seller.getFeeScale());
                        agentProfit3 = agentProfit3.subtract(proSeller);
                    }
                }
                agentProfit = agentProfit.add(agentProfit3);
            }
        }

        //2.综合管理费分成
        //获取对应角色下用户所有除了匹配中和流单以外的订单
        List<Order> orderList2 = getRoleOrder2(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(orderList2)) {
            for (Order o : orderList2) {
                //当前代理商获取的综合管理费分佣金额
                BigDecimal threeAgentFee = user.getPoundageScale().multiply(o.getPaidFee()).multiply(BigDecimal.valueOf(0.01));
                //判当前订单的客户上级是否有代理商销售
                List<User> usersList = getParentUsers(o.getUserId(), Enum.UserType.AGENTSELLER.getValue());
                Seller seller = sellerMapper.selectOne(new Seller(t -> {
                    t.setUserId(usersList.get(0).getId());
                }));
                BigDecimal feeSeller = threeAgentFee.multiply(seller.getFeeScale());
                //综合管理费减去代理商销售的分佣比例
                threeAgentFee = threeAgentFee.subtract(feeSeller);
                agentFee = agentFee.add(threeAgentFee);
            }
        }

        //3.递延费分成
        //获取递延费资金记录
        List<AccountLog> accountLogList = getRoleAccountLog(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(accountLogList)) {
            for (AccountLog accountLog : accountLogList) {
                //当前代理商的递延费分佣金额
                BigDecimal threeDeferFee = user.getDeferScale().multiply(accountLog.getAmount().multiply(BigDecimal.valueOf(0.01)));
                //判当前订单的客户上级是否有代理商销售
                List<User> usersList = getParentUsers(accountLog.getUserId(), Enum.UserType.AGENTSELLER.getValue());
                Seller seller = sellerMapper.selectOne(new Seller(t -> {
                    t.setUserId(usersList.get(0).getId());
                }));
                //递延费减去代理商销售的分佣比例
                threeDeferFee = threeDeferFee.subtract(threeDeferFee.multiply(seller.getFeeScale()));
                deferFee = deferFee.add(threeDeferFee);
            }
        }

        user.setPoundageDivide(PriceHelper.format(agentFee));
        user.setProfitDivide(PriceHelper.format(agentProfit));
        user.setDeferDivide(PriceHelper.format(deferFee));
        user.setSellerDivide(BigDecimal.ZERO);
        user.setTotalDivide((PriceHelper.format(agentFee).add(PriceHelper.format(agentProfit)).add(PriceHelper.format(deferFee))));
    }


    /**
     * 二级代理商获利计算
     */
    private void twoAgent(UserModel user, Date startTime, Date endTime) throws Exception {
        //1.盈利分成
        //获取对应角色下用户所有已结算订单
        List<Order> orderList1 = getRoleOrder1(user, startTime, endTime);
        BigDecimal agentFee = BigDecimal.ZERO;
        BigDecimal agentProfit = BigDecimal.ZERO;
        BigDecimal deferFee = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(orderList1)) {
            for (Order o : orderList1) {
                //当前订单的是否盈利
                BigDecimal agentProfit2 = BigDecimal.ZERO;
                if (o.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                    //判当前订单的客户上级是否有代理商或代理商销售
                    Integer[] types = {Enum.UserType.AGENTSELLER.getValue(), Enum.UserType.THREELEVEL.getValue()};
                    List<User> usersList = getParentUsers(o.getUserId(), types);

                    BigDecimal proDivideScale = new BigDecimal(1).subtract(o.getDivideScale());
                    //可分佣盈利利润
                    BigDecimal proDivide = o.getProfitCount().multiply(proDivideScale);
                    //获取当前代理商的盈利分佣比例
                    BigDecimal agentProfitScale = user.getProfitScale();
                    //用户若存在代理商销售则计算代理商获取的分佣
                    if (CollectionUtils.isNotEmpty(usersList)) {
                        Map<Integer, Object> uMap = new HashMap<>();
                        for (User u : usersList) {
                            uMap.put(u.getUserType(), u);
                        }
                        if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                            User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                            agentProfit2 = (agentProfitScale.subtract(user2.getProfitScale())).multiply(BigDecimal.valueOf(0.01)).multiply(proDivide);
                        } else if (uMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) & !uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                            User u = (User) uMap.get(Enum.UserType.AGENTSELLER.getValue());
                            Seller seller = sellerMapper.selectOne(new Seller(t -> {
                                t.setUserId(u.getId());
                            }));
                            agentProfit2 = agentProfitScale.multiply(proDivide).multiply(BigDecimal.valueOf(0.01));
                            BigDecimal proSeller = agentProfit2.multiply(seller.getFeeScale());
                            agentProfit2 = agentProfit2.subtract(proSeller);
                        }
                    } else {
                        agentProfit2 = agentProfitScale.multiply(proDivide).multiply(BigDecimal.valueOf(0.01));
                    }
                }
                agentProfit = agentProfit.add(agentProfit2);
            }
        }

        //2.综合管理费分成
        //获取对应角色下用户所有除了匹配中和流单以外的订单
        List<Order> orderList2 = getRoleOrder2(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(orderList2)) {
            for (Order o : orderList2) {
                //当前代理商获取的综合管理费分佣金额
                BigDecimal twoAgentFee = BigDecimal.ZERO;
                //判当前订单的客户上级是否有代理商或代理商销售
                Integer[] types = {Enum.UserType.AGENTSELLER.getValue(), Enum.UserType.THREELEVEL.getValue()};
                List<User> usersList = getParentUsers(o.getUserId(), types);

                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Map<Integer, Object> uMap = new HashMap<>();
                    for (User u : usersList) {
                        uMap.put(u.getUserType(), u);
                    }
                    if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                        twoAgentFee = (user.getPoundageScale().subtract(user2.getPoundageScale())).multiply(BigDecimal.valueOf(0.01)).multiply(o.getPaidFee());
                    } else if (uMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) && !uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User u = (User) uMap.get(Enum.UserType.AGENTSELLER.getValue());
                        Seller seller = sellerMapper.selectOne(new Seller(t -> {
                            t.setUserId(u.getId());
                        }));
                        twoAgentFee = user.getPoundageScale().multiply(o.getPaidFee()).multiply(BigDecimal.valueOf(0.01));
                        BigDecimal feeSeller = twoAgentFee.multiply(seller.getFeeScale());

                        twoAgentFee = twoAgentFee.subtract(feeSeller);
                    }
                } else {
                    twoAgentFee = user.getPoundageScale().multiply(o.getPaidFee()).multiply(BigDecimal.valueOf(0.01));
                }
                agentFee = agentFee.add(twoAgentFee);
            }
        }

        //3.递延费分成
        //获取递延费资金记录
        List<AccountLog> accountLogList = getRoleAccountLog(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(accountLogList)) {
            for (AccountLog accountLog : accountLogList) {
                //当前代理商的递延费分佣金额
                BigDecimal twoDeferFee = BigDecimal.ZERO;

                //判当前订单的客户上级是否有代理商或代理商销售
                Integer[] types = {Enum.UserType.AGENTSELLER.getValue(), Enum.UserType.THREELEVEL.getValue()};
                List<User> usersList = getParentUsers(accountLog.getUserId(), types);
                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Map<Integer, Object> uMap = new HashMap<>();
                    for (User u : usersList) {
                        uMap.put(u.getUserType(), u);
                    }
                    if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                        twoDeferFee = (user.getDeferScale().subtract(user2.getDeferScale())).multiply(BigDecimal.valueOf(0.01)).multiply(accountLog.getAmount());
                    } else if (uMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) && !uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User u = (User) uMap.get(Enum.UserType.AGENTSELLER.getValue());
                        Seller seller = sellerMapper.selectOne(new Seller(t -> {
                            t.setUserId(u.getId());
                        }));
                        twoDeferFee = user.getDeferScale().multiply(accountLog.getAmount()).multiply(BigDecimal.valueOf(0.01));
                        twoDeferFee = twoDeferFee.subtract(twoDeferFee.multiply(seller.getFeeScale()));
                    }
                } else {
                    twoDeferFee = user.getDeferScale().multiply(accountLog.getAmount().multiply(BigDecimal.valueOf(0.01)));
                }
                deferFee = deferFee.add(twoDeferFee);
            }
        }
        user.setPoundageDivide(PriceHelper.format(agentFee));
        user.setProfitDivide(PriceHelper.format(agentProfit));
        user.setDeferDivide(PriceHelper.format(deferFee));
        user.setSellerDivide(BigDecimal.ZERO);
        user.setTotalDivide((PriceHelper.format(agentFee).add(PriceHelper.format(agentProfit)).add(PriceHelper.format(deferFee))));
    }

    /**
     * 一级代理商获利计算
     */
    private void oneAgent(UserModel user, Date startTime, Date endTime) throws Exception {
        //1.盈利分成
        //获取对应角色下用户所有已结算订单
        List<Order> orderList1 = getRoleOrder1(user, startTime, endTime);
        BigDecimal agentFee = BigDecimal.ZERO;
        BigDecimal agentProfit = BigDecimal.ZERO;
        BigDecimal deferFee = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(orderList1)) {
            for (Order o : orderList1) {
                //当前订单的是否盈利
                BigDecimal agentProfit2 = BigDecimal.ZERO;
                if (o.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                    //判当前订单的客户上级是否有代理商或代理商销售
                    Integer[] types = {Enum.UserType.AGENTSELLER.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue()};
                    List<User> usersList = getParentUsers(o.getUserId(), types);

                    BigDecimal proDivideScale = new BigDecimal(1).subtract(o.getDivideScale());
                    //可分佣盈利利润
                    BigDecimal proDivide = o.getProfitCount().multiply(proDivideScale);
                    //获取当前代理商的盈利分佣比例
                    BigDecimal agentProfitScale = user.getProfitScale();
                    //用户若存在代理商销售则计算代理商获取的分佣
                    if (CollectionUtils.isNotEmpty(usersList)) {
                        Map<Integer, Object> uMap = new HashMap<>();
                        for (User u : usersList) {
                            uMap.put(u.getUserType(), u);
                        }
                        if (uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                            User user2 = (User) uMap.get(Enum.UserType.TWOLEVEL.getValue());
                            agentProfit2 = (agentProfitScale.subtract(user2.getProfitScale())).multiply(BigDecimal.valueOf(0.01)).multiply(proDivide);
                        } else if (uMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) & !uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                            User u = (User) uMap.get(Enum.UserType.AGENTSELLER.getValue());
                            Seller seller = sellerMapper.selectOne(new Seller(t -> {
                                t.setUserId(u.getId());
                            }));
                            agentProfit2 = agentProfitScale.multiply(proDivide).multiply(BigDecimal.valueOf(0.01));
                            BigDecimal proSeller = agentProfit2.multiply(seller.getFeeScale());
                            agentProfit2 = agentProfit2.subtract(proSeller);
                        }
                    } else {
                        agentProfit2 = agentProfitScale.multiply(proDivide).multiply(BigDecimal.valueOf(0.01));
                    }
                }
                agentProfit = agentProfit.add(agentProfit2);
            }
        }

        //2.综合管理费分成
        //获取对应角色下用户所有除了匹配中和流单以外的订单
        List<Order> orderList2 = getRoleOrder2(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(orderList2)) {
            for (Order o : orderList2) {
                //当前代理商获取的综合管理费分佣金额
                BigDecimal oneAgentFee = BigDecimal.ZERO;
                //判当前订单的客户上级是否有代理商或代理商销售
                Integer[] types = {Enum.UserType.AGENTSELLER.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue()};
                List<User> usersList = getParentUsers(o.getUserId(), types);

                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Map<Integer, Object> uMap = new HashMap<>();
                    for (User u : usersList) {
                        uMap.put(u.getUserType(), u);
                    }
                    if (uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.TWOLEVEL.getValue());
                        oneAgentFee = (user.getPoundageScale().subtract(user2.getPoundageScale())).multiply(BigDecimal.valueOf(0.01)).multiply(o.getPaidFee());
                    } else if (uMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) && !uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                        User u = (User) uMap.get(Enum.UserType.AGENTSELLER.getValue());
                        Seller seller = sellerMapper.selectOne(new Seller(t -> {
                            t.setUserId(u.getId());
                        }));
                        oneAgentFee = user.getPoundageScale().multiply(o.getPaidFee()).multiply(BigDecimal.valueOf(0.01));
                        BigDecimal feeSeller = oneAgentFee.multiply(seller.getFeeScale());

                        oneAgentFee = oneAgentFee.subtract(feeSeller);
                    }
                } else {
                    oneAgentFee = user.getPoundageScale().multiply(o.getPaidFee()).multiply(BigDecimal.valueOf(0.01));
                }
                agentFee = agentFee.add(oneAgentFee);
            }
        }

        //3.递延费分成
        //获取递延费资金记录
        List<AccountLog> accountLogList = getRoleAccountLog(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(accountLogList)) {
            for (AccountLog accountLog : accountLogList) {
                //当前代理商的递延费分佣金额
                BigDecimal oneDeferFee = BigDecimal.ZERO;

                //判当前订单的客户上级是否有代理商或代理商销售
                Integer[] types = {Enum.UserType.AGENTSELLER.getValue(), Enum.UserType.THREELEVEL.getValue()};
                List<User> usersList = getParentUsers(accountLog.getUserId(), types);
                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Map<Integer, Object> uMap = new HashMap<>();
                    for (User u : usersList) {
                        uMap.put(u.getUserType(), u);
                    }
                    if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                        oneDeferFee = (user.getDeferScale().subtract(user2.getDeferScale())).multiply(BigDecimal.valueOf(0.01)).multiply(accountLog.getAmount());
                    } else if (uMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) && !uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User u = (User) uMap.get(Enum.UserType.AGENTSELLER.getValue());
                        Seller seller = sellerMapper.selectOne(new Seller(t -> {
                            t.setUserId(u.getId());
                        }));
                        oneDeferFee = user.getDeferScale().multiply(accountLog.getAmount()).multiply(BigDecimal.valueOf(0.01));
                        oneDeferFee = oneDeferFee.subtract(oneDeferFee.multiply(seller.getFeeScale()));
                    }
                } else {
                    oneDeferFee = user.getDeferScale().multiply(accountLog.getAmount().multiply(BigDecimal.valueOf(0.01)));
                }
                deferFee = deferFee.add(oneDeferFee);
            }
        }
        user.setPoundageDivide(PriceHelper.format(agentFee));
        user.setProfitDivide(PriceHelper.format(agentProfit));
        user.setDeferDivide(PriceHelper.format(deferFee));
        user.setSellerDivide(BigDecimal.ZERO);
        user.setTotalDivide((PriceHelper.format(agentFee).add(PriceHelper.format(agentProfit)).add(PriceHelper.format(deferFee))));
    }

    /**
     * 代理商销售
     */
    private void agentSeller(UserModel user, Date startTime, Date endTime) throws Exception {
        //1.盈利分成
        //获取对应角色下用户所有已结算订单
        List<Order> orderList1 = getRoleOrder1(user, startTime, endTime);
        BigDecimal sellerFee = BigDecimal.ZERO;
        BigDecimal sellerProfit = BigDecimal.ZERO;
        BigDecimal sellerDefer = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(orderList1)) {
            for (Order o : orderList1) {
                //当前订单的是否盈利
                BigDecimal sellerProfit2 = BigDecimal.ZERO;
                if (o.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                    //判当前订单的客户上级是否有代理商
                    Integer[] types = {Enum.UserType.ONELEVEL.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue()};
                    List<User> usersList = getParentUsers(o.getUserId(), types);

                    BigDecimal proDivideScale = new BigDecimal(1).subtract(o.getDivideScale());
                    //可分佣盈利利润
                    BigDecimal proDivide = o.getProfitCount().multiply(proDivideScale);
                    //获取当前代理商的盈利分佣比例
                    BigDecimal agentProfitScale = user.getProfitScale();
                    //用户若存在代理商销售则计算代理商获取的分佣
                    if (CollectionUtils.isNotEmpty(usersList)) {
                        Map<Integer, Object> uMap = new HashMap<>();
                        for (User u : usersList) {
                            uMap.put(u.getUserType(), u);
                        }
                        if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                            User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                            sellerProfit2 = (agentProfitScale.subtract(user2.getProfitScale())).multiply(BigDecimal.valueOf(0.01)).multiply(proDivide);
                        } else if (uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                            User user2 = (User) uMap.get(Enum.UserType.TWOLEVEL.getValue());
                            sellerProfit2 = (agentProfitScale.subtract(user2.getProfitScale())).multiply(BigDecimal.valueOf(0.01)).multiply(proDivide);
                        } else if (uMap.containsKey(Enum.UserType.ONELEVEL.getValue())) {
                            User user2 = (User) uMap.get(Enum.UserType.ONELEVEL.getValue());
                            sellerProfit2 = (agentProfitScale.subtract(user2.getProfitScale())).multiply(BigDecimal.valueOf(0.01)).multiply(proDivide);
                        }
                    }
                }
                sellerProfit = sellerProfit.add(sellerProfit2);
            }
        }

        //2.综合管理费分成
        //获取对应角色下用户所有除了匹配中和流单以外的订单
        List<Order> orderList2 = getRoleOrder2(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(orderList2)) {
            for (Order o : orderList2) {
                //当前代理商获取的综合管理费分佣金额
                BigDecimal sellerFee2 = BigDecimal.ZERO;
                //判当前订单的客户上级是否有代理商或代理商销售
                Integer[] types = {Enum.UserType.ONELEVEL.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue()};
                List<User> usersList = getParentUsers(o.getUserId(), types);

                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Map<Integer, Object> uMap = new HashMap<>();
                    for (User u : usersList) {
                        uMap.put(u.getUserType(), u);
                    }
                    if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                        sellerFee2 = (user.getPoundageScale().subtract(user2.getPoundageScale())).multiply(BigDecimal.valueOf(0.01)).multiply(o.getPaidFee());
                    } else if (uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.TWOLEVEL.getValue());
                        sellerFee2 = (user.getPoundageScale().subtract(user2.getPoundageScale())).multiply(BigDecimal.valueOf(0.01)).multiply(o.getPaidFee());
                    } else if (uMap.containsKey(Enum.UserType.ONELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.ONELEVEL.getValue());
                        sellerFee2 = (user.getPoundageScale().subtract(user2.getPoundageScale())).multiply(BigDecimal.valueOf(0.01)).multiply(o.getPaidFee());
                    }
                }
                sellerFee = sellerFee.add(sellerFee2);
            }
        }

        //3.递延费分成
        //获取递延费资金记录
        List<AccountLog> accountLogList = getRoleAccountLog(user, startTime, endTime);
        if (CollectionUtils.isNotEmpty(accountLogList)) {
            for (AccountLog accountLog : accountLogList) {
                //当前代理商的递延费分佣金额
                BigDecimal sellerDeferFee = BigDecimal.ZERO;

                //判当前订单的客户上级是否有代理商或代理商销售
                Integer[] types = {Enum.UserType.ONELEVEL.getValue(), Enum.UserType.THREELEVEL.getValue(), Enum.UserType.TWOLEVEL.getValue()};
                List<User> usersList = getParentUsers(accountLog.getUserId(), types);
                //用户若存在代理商销售则计算代理商获取的分佣
                if (CollectionUtils.isNotEmpty(usersList)) {
                    Map<Integer, Object> uMap = new HashMap<>();
                    for (User u : usersList) {
                        uMap.put(u.getUserType(), u);
                    }
                    if (uMap.containsKey(Enum.UserType.THREELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.THREELEVEL.getValue());
                        sellerDeferFee = (user.getDeferScale().subtract(user2.getDeferScale())).multiply(BigDecimal.valueOf(0.01)).multiply(accountLog.getAmount());
                    } else if (uMap.containsKey(Enum.UserType.TWOLEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.TWOLEVEL.getValue());
                        sellerDeferFee = (user.getDeferScale().subtract(user2.getDeferScale())).multiply(BigDecimal.valueOf(0.01)).multiply(accountLog.getAmount());
                    } else if (uMap.containsKey(Enum.UserType.ONELEVEL.getValue())) {
                        User user2 = (User) uMap.get(Enum.UserType.ONELEVEL.getValue());
                        sellerDeferFee = (user.getDeferScale().subtract(user2.getDeferScale())).multiply(BigDecimal.valueOf(0.01)).multiply(accountLog.getAmount());
                    }
                }
                sellerDefer = sellerDefer.add(sellerDeferFee);
            }
        }
        user.setPoundageDivide(PriceHelper.format(sellerFee));
        user.setProfitDivide(PriceHelper.format(sellerProfit));
        user.setDeferDivide(PriceHelper.format(sellerDefer));
        user.setSellerDivide(BigDecimal.ZERO);
        user.setTotalDivide((PriceHelper.format(sellerFee).add(PriceHelper.format(sellerProfit)).add(PriceHelper.format(sellerDefer))));
    }

    /**
     * 存在代理商时，处理业务
     */
    private Map<Integer, BigDecimal> agent(HashMap<Integer, Object> typeMap, Order order, BigDecimal paidFee, BigDecimal platFee, BigDecimal platProfit, BigDecimal defer, BigDecimal platDefer) throws Exception {
        Map<Integer, BigDecimal> mapB = new HashMap<>();
        if (typeMap.containsKey(Enum.UserType.NEXTSELLER.getValue())) {
            User nsUser = (User) typeMap.get(Enum.UserType.NEXTSELLER.getValue());
            Seller seller = sellerMapper.selectOne(new Seller(t -> {
                t.setUserId(nsUser.getId());
            }));
            //次销售佣金
            BigDecimal sellerFee2 = PriceHelper.format(order.getTradeCredit().multiply(BigDecimal.valueOf(10000)).multiply(seller.getFeeScale()));
            platFee = platFee.add(paidFee.subtract(sellerFee2));
            //如果盈利
            if (order.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal proDivideScale = new BigDecimal(1).subtract(order.getDivideScale());
                //可分佣盈利利润
                BigDecimal proDivide = order.getProfitCount().multiply(proDivideScale);
                platProfit = platProfit.add(proDivide);//盈利利润
            }
        } else if (typeMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) || typeMap.containsKey(Enum.UserType.THREELEVEL.getValue()) || typeMap.containsKey(Enum.UserType.TWOLEVEL.getValue()) || typeMap.containsKey(Enum.UserType.ONELEVEL.getValue())) {
            //无论存在几级代理商和代理商销售，若客户上级不是次销售和平台，则平台利润都以一级代理商佣金比例扣除
            User one = (User) typeMap.get(Enum.UserType.ONELEVEL.getValue());
            //获取一级代理商的手续费分佣比例
            BigDecimal poundageScale = one.getPoundageScale();
            //获取一级代理商的手续费分佣比例
            BigDecimal fee;
            if (paidFee.compareTo(BigDecimal.ZERO) > 0) {
                fee = PriceHelper.format((BigDecimal.ONE.subtract(poundageScale.multiply(BigDecimal.valueOf(0.01)))).multiply(paidFee));
            } else {
                fee = PriceHelper.format(paidFee);
            }
            platFee = platFee.add(fee);
            //递延费
            BigDecimal deferScale = one.getDeferScale();
            if (defer.compareTo(BigDecimal.ZERO) > 0) {
                platDefer = platDefer.add(BigDecimal.ONE.subtract(deferScale.multiply(BigDecimal.valueOf(0.01))).multiply(defer));
            }
            //如果盈利
            if (order.getStatus() == Order.STATUS.T7.code && order.getProfitCount().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal proDivideScale = new BigDecimal(1).subtract(order.getDivideScale());
                //可分佣盈利利润
                BigDecimal proDivide = order.getProfitCount().multiply(proDivideScale);
                //获取一级代理商的盈利分佣比例
                BigDecimal profitScale = one.getProfitScale();
                BigDecimal profit = PriceHelper.format((BigDecimal.ONE.subtract(profitScale.multiply(BigDecimal.valueOf(0.01)))).multiply(proDivide));
                platProfit = platProfit.add(profit);//盈利利润
            }
        }
        mapB.put(0, platFee);
        mapB.put(1, platProfit);
        mapB.put(2, platDefer);
        return mapB;
    }


    private Map<Integer, BigDecimal> agent(HashMap<Integer, Object> typeMap, BigDecimal defer, BigDecimal platDefer) throws Exception {
        Map<Integer, BigDecimal> mapB = new HashMap<>();
        if (typeMap.containsKey(Enum.UserType.NEXTSELLER.getValue())) {

        } else if (typeMap.containsKey(Enum.UserType.AGENTSELLER.getValue()) || typeMap.containsKey(Enum.UserType.THREELEVEL.getValue()) || typeMap.containsKey(Enum.UserType.TWOLEVEL.getValue()) || typeMap.containsKey(Enum.UserType.ONELEVEL.getValue())) {
            //无论存在几级代理商和代理商销售，若客户上级不是次销售和平台，则平台利润都以一级代理商佣金比例扣除
            User one = (User) typeMap.get(Enum.UserType.ONELEVEL.getValue());
            //递延费
            BigDecimal deferScale = one.getDeferScale();
            if (defer.compareTo(BigDecimal.ZERO) > 0) {
                platDefer = platDefer.add(BigDecimal.ONE.subtract(deferScale.multiply(BigDecimal.valueOf(0.01))).multiply(defer));
            }
        }
        mapB.put(0, platDefer);
        return mapB;
    }

    private List<Order> getRoleOrder1(UserModel user, Date startTime, Date endTime) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("code", user.getCode());
        data.put("level", 0);
        List<User> userList = userMapper.listPartnerByLevel(data);
        String userIds = "0";
        if (CollectionUtils.isNotEmpty(userList)) {
            userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
        }
        HashMap<String, Object> mapSql = new HashMap<>();
        mapSql.put("startTime", startTime);
        mapSql.put("endTime", endTime);
        mapSql.put("userIds", userIds);
        mapSql.put("status", Order.STATUS.T7.code);
        return orderMapper.selectOrderWithTime1(mapSql);
    }

    private List<Order> getRoleOrder2(UserModel user, Date startTime, Date endTime) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("code", user.getCode());
        data.put("level", 0);
        List<User> userList = userMapper.listPartnerByLevel(data);
        String userIds = "0";
        if (CollectionUtils.isNotEmpty(userList)) {
            userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
        }
        HashMap<String, Object> mapSql = new HashMap<>();
        mapSql.put("startTime", startTime);
        mapSql.put("endTime", endTime);
        mapSql.put("userIds", userIds);
        return orderMapper.selectOrderWithTime2(mapSql);
    }

    private List<AccountLog> getRoleAccountLog(UserModel user, Date startTime, Date endTime) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("code", user.getCode());
        data.put("level", 0);
        List<User> userList = userMapper.listPartnerByLevel(data);
        String userIds = "0";
        if (CollectionUtils.isNotEmpty(userList)) {
            userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
        }
        HashMap<String, Object> mapSql = new HashMap<>();
        mapSql.put("startTime", startTime);
        mapSql.put("endTime", endTime);
        mapSql.put("userIds", userIds);
        mapSql.put("type", AccountLog.TYPE.T12.code);
        return accountLogMapper.selectAccountLogWithTime(mapSql);
    }


    /**
     * 计算 订单的平台毛利润
     *
     * @param o
     * @return
     * @throws Exception
     */
    private BigDecimal platformProfit(Order o) throws Exception {
        //获取当前订单的平台毛利润，毛利润 = 综合管理费+递延费- 双向佣金-利息-手续费（过户费、印花税）
        //计算 （过户费、印花税）
        BigDecimal fee = o.getSellDealPrice().multiply(new BigDecimal(o.getSellDealNumber())).multiply(new BigDecimal(0.001));//过户费和印花税算千一
        //计算利息（每一万每天的额度*点卖额度*天数）
        BigDecimal buyInterest = redisService.get(ConfigNID.BUY_INTEREST, BigDecimal.class);
        BigDecimal interest = buyInterest.multiply(o.getTradeCredit()).multiply((new BigDecimal(2)).add(new BigDecimal(o.getDiyanTime())));
        //计算佣金
        Invest invest = investService.selectOne(new Invest(t -> {
            t.setUserId(o.getInvestorId());
        }));
        //买入佣金
        //佣金 = 买入成交价格 * 数量 *佣金比例
        BigDecimal scale = invest.getFeeScale();
        //计算佣金
        //股票买入出成交价格*数量
        BigDecimal buyAuo = o.getBuyDealPrice().multiply(BigDecimal.valueOf(o.getBuyDealNumber()));
        BigDecimal commisBuy = scale.multiply(buyAuo);
        if (PriceHelper.isLessThan(commisBuy, new BigDecimal("5"))) {
            commisBuy = BigDecimal.valueOf(5);
        }
        //股票买入出成交价格*数量
        BigDecimal sellAuo = o.getSellDealPrice().multiply(BigDecimal.valueOf(o.getSellDealNumber()));
        BigDecimal commisSell = scale.multiply(sellAuo);
        if (PriceHelper.isLessThan(commisSell, new BigDecimal("5"))) {
            commisSell = BigDecimal.valueOf(5);
        }
        //平台总成本 = 佣金+过户费+印花税+利息
        BigDecimal totalFee = PriceHelper.format(fee.add(interest).add(commisBuy).add(commisSell));
        //计算剩余手续费的利润 = 综合管理费+递延—成本
        BigDecimal feeProfit = PriceHelper.format((o.getPaidFee().add(o.getPaidDiyan())).subtract(totalFee));
        //总手续费的计算公式：（18/38*综合交易管理费+递延费）*分成比例

//        BigDecimal feeProfit = BigDecimal.valueOf(18).divide(BigDecimal.valueOf(38), 2).multiply(o.getPaidDiyan().add(o.getPaidFee()));

        return feeProfit;
    }

    /**
     * 获取用户的上级
     *
     * @param userId 用户id
     * @param types  上级类型
     * @return
     * @throws Exception
     */
    private List<User> getParentUsers(Integer userId, Integer... types) throws Exception {
        User user = userMapper.selectByPrimaryKey(userId);
        Integer level = user.getLevel();
        Integer parentId = user.getInviteId();
        User parentUser = null;

        List<User> userList = new ArrayList<>();
        if (level > 1) {
            //上级
            for (int i = level - 1; i > 0; i--) {
                parentUser = userMapper.selectByPrimaryKey(parentId);
                if (parentUser != null) {
                    Integer p = parentUser.getUserType();
                    for (int j = 0; j < types.length; j++) {
                        if (p == types[i]) {
                            userList.add(parentUser);
                        }
                    }
                }
                parentId = parentUser.getInviteId();
            }
        }
        return userList;
    }

    /**
     * 查找所属上级用户名
     *
     * @param user
     * @throws Exception
     */
    private void findParent(UserModel user, Integer... types) throws Exception {
        Integer level = user.getLevel();
        Integer parentId = user.getInviteId();
        User parentUser = null;
        if (level > 1) {
            //上级
            for (int i = level - 1; i > 0; i--) {
                parentUser = userMapper.selectByPrimaryKey(parentId);
                if (parentUser != null) {
                    Integer p = parentUser.getUserType();
                    for (int j = 0; j < types.length; j++) {
                        if (p == types[i]) {
                            user.setInvestName(parentUser.getUserName());
                            break;
                        }
                    }
                }
                parentId = parentUser.getInviteId();
            }
        }
    }
}
